package demo;

import static demo.utils.ColorUtils.*;
import ru.nsu.fit.iconveyor.conveyor.node.InnerNode;
import ru.nsu.fit.iconveyor.conveyor.node.NodeConnection;

import java.awt.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ToBlackAndWhiteNode extends InnerNode {
    public static final String INPUT_IMAGE = "input_image";
    public static final String OUTPUT_IMAGE = "output_image";

    private final NodeConnection<Image> inputImage;
    private final NodeConnection<Image> outputImage;

    public ToBlackAndWhiteNode(String id) {
        super(id);

        inputImage = new NodeConnection<Image>(Image.class, NodeConnection.Type.INPUT, INPUT_IMAGE);
        outputImage = new NodeConnection<Image>(Image.class, NodeConnection.Type.OUTPUT, OUTPUT_IMAGE);

        addNodeConnection(inputImage);
        addNodeConnection(outputImage);
    }

    @Override
    public int getOutputToInputRatio() {
        return 1;
    }

    @Override
    public Map<String, Object> preExecute(Map<String, Object> availableInputBundles, Properties prop) {
        if(availableInputBundles.containsKey(INPUT_IMAGE)) {
            return availableInputBundles;
        }
        return null;
    }

    @Override
    public Map<String, Object> execute(Map<String, Object> inputBundles, Properties prop) {
        Image inputImage = (Image)inputBundles.get(INPUT_IMAGE);
        final int [][] inputBitmap = inputImage.getBitmap();
        final int width = inputBitmap.length;
        final int height = inputBitmap[0].length;
        final int [][] outputBitmap = new int[width][height];
        for(int i = 0 ; i < width ; ++i) {
            for(int j = 0 ; j < height ; ++j) {
                final int rgbInt = inputBitmap[i][j];
                int r = getR(rgbInt);
                int g = getG(rgbInt);
                int b = getB(rgbInt);
                float [] hsb = new float[3];
                Color.RGBtoHSB(r, g, b, hsb);

                int greyRGB = Color.HSBtoRGB(hsb[0], 0, hsb[2]);
                outputBitmap[i][j] = greyRGB;
            }
        }
        final Image outputImage = new Image();
        outputImage.setBitmap(outputBitmap);
        outputImage.setName(inputImage.getName());
        return new HashMap<String, Object>() {
            {
                put(OUTPUT_IMAGE, outputImage);
            }
        };
    }

}
